package com.hot100;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

public class PriorityQueueTask {


    public int[] topKFrequent(int[] nums, int k) {
        //<num,count>
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            map.put(num,map.getOrDefault(num,0)+1);
        }

        PriorityQueue<Map.Entry<Integer, Integer>> queue = new PriorityQueue<>(
                Comparator.comparingInt(Map.Entry::getValue));

        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            if(queue.size()<k) {
                queue.offer(entry);
            } else {
                if(entry.getValue()>queue.peek().getValue()) {
                    queue.poll();
                    queue.offer(entry);
                }
            }
        }

        int[] result = new int[k];


        for (int i = 0; i < k; i++) {
            Integer value = queue.poll().getKey();
            result[i]=value;
        }

        return result;
    }


}
